package com.pactera.android.db;

import com.pactera.android.util.Constants;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;

public class ContactListDB {
	
	static final String TAG = "ContactListDB";
	
	public static final String ID = BaseColumns._ID;
	public static final String NAME = "name";
	public static final String MOBILE = "mobile";
	
	private Context context;
	private static final int VERSION = 1;
	private DatabaseHelper dbHelper = null;
	private SQLiteDatabase sqlDB = null;
		
	
	public ContactListDB(Context ctx){		
		this.context = ctx;
	}
	
	public  void OpenDB(){
		
		dbHelper = new DatabaseHelper(context, Constants.DB_SCHEMA);
		sqlDB = dbHelper.getWritableDatabase();
	}
	
	public void CloseDb(){
		dbHelper.close();
    }
	
	public int insertOrUpdate(String table, String nullColumnHack, ContentValues values) {
		Log.d(TAG, "insertOrUpdate");
		int ret = sqlDB.update(table, values, ID + " = '" + values.getAsString(ID) + "'", null);
		if (ret == 0) {
			ret = (int) sqlDB.insert(table, nullColumnHack, values);
		}

		return ret;
	}
	
	public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy){
		 return sqlDB.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
	}
	
	
	
	public class DatabaseHelper extends SQLiteOpenHelper {
		
		public  DatabaseHelper(Context context, String name, CursorFactory cursorFactory, int version) {			
			super(context, name, cursorFactory, version);
		}

		public  DatabaseHelper(Context context, String name, int version) {			
			super(context, name, null, version);
		}
		
		public  DatabaseHelper(Context context, String name) {
			super(context, name, null, VERSION);
		}

		
		@Override
		public void onCreate(SQLiteDatabase db) {
			//Invoked at the first time when the db is created
			db.execSQL("CREATE TABLE "+ Constants.CONTACT_LIST_TABLE + " (" +
                    ID + " INTEGER PRIMARY KEY," +                    
                    NAME + " TEXT," +
                    MOBILE + " TEXT" +                    
                    ");");						
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.d(TAG, "onUpgrade");
			db.execSQL("drop table if exists " + Constants.CONTACT_LIST_TABLE);
		}

		@Override
		public void onOpen(SQLiteDatabase db) {
			//Invoked when the DB is opend
			super.onOpen(db);
		}
	}
	
}
